package com.huluobo.a2302mdmdemo.pages

import android.util.Log
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Send
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Icon
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshots.SnapshotStateList
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.viewinterop.AndroidView
import androidx.navigation.NavHostController
import coil.compose.AsyncImage
import com.google.gson.Gson
import com.huluobo.a2302mdmdemo.R
import com.huluobo.a2302mdmdemo.demo.RedPackRainView
import com.huluobo.lib_base.BaseTitle
import com.hyphenate.EMCallBack
import com.hyphenate.EMMessageListener
import com.hyphenate.chat.EMClient
import com.hyphenate.chat.EMMessage
import com.hyphenate.chat.EMMessage.ChatType
import com.hyphenate.chat.EMTextMessageBody
import com.hyphenate.util.DateUtils
import kotlinx.coroutines.launch
import java.text.SimpleDateFormat

/**
 *  Created by LC on 2025/8/7.
 */

//声明聊天的Bean,传递联系人和聊天类型(单聊,群聊,聊天室)
data class ChatBean(val contact: String, val chatType: ChatType, val name: String = "")

@Composable
fun ChatPage(navHostController: NavHostController, json: String) {
    val chatBean = Gson().fromJson(json, ChatBean::class.java)

    //消息列表的数据源
    val messageList = remember {
        SnapshotStateList<EMMessage>()
    }

    //发送的消息
    var messageString by remember {
        mutableStateOf("")
    }

    //是否显示发送消息的进度条
    var isShowProgress by remember {
        mutableStateOf(false)
    }

    //是否显示错误图标
    var isError by remember {
        mutableStateOf(false)
    }

    //是否显示时间
    var isShowTime by remember {
        mutableStateOf(false)
    }

    //是否显示爱心雨
    var isShowLove by remember {
        mutableStateOf(false)
    }

    //消息列表的状态
    var listState = rememberLazyListState()

    //控制滚动的协程作用域
    val coroutineScope = rememberCoroutineScope()

    //消息监听器
    val messageListener = EMMessageListener {
        messageList.addAll(it)
        //接收到新消息的时候,控制协程跳转列表的最后一位
        coroutineScope.launch {
            listState.scrollToItem(messageList.size - 1)
        }
    }

    //通过会话列表获取历史消息
    val emConversation = EMClient.getInstance().chatManager().getConversation(chatBean.contact)
    if (emConversation != null) {
        messageList.clear()
        messageList.addAll(emConversation.allMessages)
    }

    DisposableEffect(Unit) {
        //初始化时添加消息监听器
        EMClient.getInstance().chatManager().addMessageListener(messageListener)
        onDispose {
            //页面销毁时,移除消息监听器
            EMClient.getInstance().chatManager().removeMessageListener(messageListener)
        }
    }

    Scaffold(
        bottomBar = {
            OutlinedTextField(
                value = messageString,
                onValueChange = { messageString = it },
                Modifier.fillMaxWidth(),
                trailingIcon = {
                    Icon(imageVector = Icons.Default.Send, contentDescription = "", modifier = Modifier.clickable {
                        if (messageString.isNotEmpty()) {
                            isShowProgress = true
                            //构建一条文本消息
                            val emMessage = EMMessage.createTextSendMessage(messageString, chatBean.contact)
                            //设置消息类型
                            emMessage.chatType = chatBean.chatType
                            //不管发送消息的状态是成功还是失败,都可以展示到消息列表中
                            messageList.add(emMessage)
                            emMessage.setMessageStatusCallback(object : EMCallBack {
                                override fun onSuccess() {
                                    //发送消息成功,清空输入框,取消发送消息的进度条
                                    messageString = ""
                                    isShowProgress = false
                                    isError = false
//                                    if (messageString.contains("爱你")) {
//                                        isShowLove = true
//                                    }
                                    //接收到新消息的时候,控制协程跳转列表的最后一位
                                    coroutineScope.launch {
                                        listState.scrollToItem(messageList.size - 1)
                                    }
                                }

                                override fun onError(code: Int, error: String?) {
                                    Log.e("TagA", "发送消息失败:$code,error:$error")
                                    isShowProgress = false
                                    //弹出错误图标
                                    isError = true
                                }
                            })
                            //发送消息
                            EMClient.getInstance().chatManager().sendMessage(emMessage)
                        }
                    })
                })
        }
    ) {
        Column(
            modifier = Modifier
                .padding(it)
                .padding(20.dp)
                .fillMaxWidth()
        ) {
            if (chatBean.chatType == ChatType.GroupChat) {
                BaseTitle(title = "讨论组-${chatBean.name}", navHostController = navHostController)
            } else {
                BaseTitle(title = "与${chatBean.contact}聊天", navHostController = navHostController)
            }
            Spacer(modifier = Modifier.height(10.dp))
            LazyColumn(state = listState, content = {
                //带下标的items
                itemsIndexed(messageList) { index: Int, item: EMMessage ->
                    //判断当前消息是否是第一条,如果是,肯定显示时间
                    if (index == 0) {
                        isShowTime = true
                    } else {
                        isShowTime =
                            !DateUtils.isCloseEnough(messageList[index].msgTime, messageList[index - 1].msgTime)
                    }

                    ChatItem(
                        message = item,
                        isShowProgress = isShowProgress,
                        index == messageList.lastIndex,
                        isError,
                        isShowTime
                    ) {
                        isShowProgress = true
                        isError = false
                        //构建一条文本消息
                        val emMessage = EMMessage.createTextSendMessage(messageString, chatBean.contact)
                        //设置消息类型
                        emMessage.chatType = chatBean.chatType
                        //不管发送消息的状态是成功还是失败,都可以展示到消息列表中
                        emMessage.setMessageStatusCallback(object : EMCallBack {
                            override fun onSuccess() {
                                //发送消息成功,清空输入框,取消发送消息的进度条
                                messageString = ""
                                isShowProgress = false
                                isError = false
                            }

                            override fun onError(code: Int, error: String?) {
                                Log.e("TagA", "发送消息失败:$code,error:$error")
                                isShowProgress = false
                                //弹出错误图标
                                isError = true
                            }
                        })
                        //发送消息
                        EMClient.getInstance().chatManager().sendMessage(emMessage)
                    }
                }
            }, verticalArrangement = Arrangement.spacedBy(10.dp))

            if (messageString.contains("爱你")) {
                LoveView()
            }
        }
    }
}

@Composable
fun LoveView() {
    AndroidView(factory = {
        val redPackRainView = RedPackRainView(it)
        redPackRainView.start()
        redPackRainView
    }, modifier = Modifier.fillMaxSize())
}

@Composable
fun ChatItem(
    message: EMMessage,
    isShowProgress: Boolean,
    isLast: Boolean,
    isError: Boolean,
    isShowTime: Boolean,
    retry: () -> Unit
) {
    if (message.direct() == EMMessage.Direct.SEND) {
        //发送的消息布局
        Column(horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier.fillMaxWidth()) {
            if (isShowTime) {
                val time = SimpleDateFormat("HH:mm:ss").format(message.msgTime)
                Text(text = "$time", color = Color.LightGray, fontSize = 13.sp)
            }
            Row(
                horizontalArrangement = Arrangement.End,
                verticalAlignment = Alignment.CenterVertically,
                modifier = Modifier
                    .padding(10.dp)
                    .fillMaxWidth()
            ) {
                if (isShowProgress && isLast) {
                    CircularProgressIndicator(Modifier.size(20.dp))
                }

                if (isError && isLast) {
                    Icon(
                        painter = painterResource(id = R.drawable.baseline_error_24),
                        contentDescription = "",
                        tint = Color.Red, modifier = Modifier.clickable {
                            //发送消息错误的重试点击事件
                            retry()
                        }
                    )
                }
                Spacer(modifier = Modifier.width(10.dp))
                Text(text = (message.body as EMTextMessageBody).message)
                Spacer(modifier = Modifier.width(10.dp))
                AsyncImage(
                    model = "https://img0.baidu.com/it/u=788800651,2030194952&fm=253&app=120&size=w931&n=0&f=JPEG&fmt=auto?sec=1730307600&t=9c17b588a934b0ccf76349e5e5b7ca08",
                    contentDescription = "",
                    modifier = Modifier
                        .size(40.dp)
                        .clip(RoundedCornerShape(5.dp)),
                    contentScale = ContentScale.Crop
                )
            }
        }
    } else {
        //接收的消息
        Column(horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier.fillMaxWidth()) {
            if (isShowTime) {
                val time = SimpleDateFormat("HH:mm:ss").format(message.msgTime)
                Text(text = "$time", color = Color.LightGray, fontSize = 13.sp)
            }
            Row(
                horizontalArrangement = Arrangement.Start,
                verticalAlignment = Alignment.CenterVertically,
                modifier = Modifier
                    .padding(10.dp)
                    .fillMaxWidth()
            ) {
                AsyncImage(
                    model = "https://img0.baidu.com/it/u=788800651,2030194952&fm=253&app=120&size=w931&n=0&f=JPEG&fmt=auto?sec=1730307600&t=9c17b588a934b0ccf76349e5e5b7ca08",
                    contentDescription = "",
                    modifier = Modifier
                        .size(40.dp)
                        .clip(RoundedCornerShape(5.dp)),
                    contentScale = ContentScale.Crop
                )
                Spacer(modifier = Modifier.width(10.dp))
                Text(text = (message.body as EMTextMessageBody).message)
            }
        }
    }

}